const arr = global.get("points");
if (!arr || arr.length === 0) return;

// 先筛选出所有OP10的点并按地址排序
const op10Points = arr
    .filter(tag => (tag[0] === '__NAME__' && tag[2] === '读'))
    .map(tag => {
        // 根据数据类型确定长度
        const dataType = tag[6];
        const length = (dataType === 'uint16' || dataType === 'bool') ? 1 : 2;
        
        return {
            tag: tag,
            address: parseInt(tag[1]),
            length: length
        };
    })
    .sort((a, b) => a.address - b.address);

let startAddress = null;
let currentAddress = null;
let currentLength = null;
let quantity = 0;
let tags = [];

function sendReadRequest(start, qty, tags) {
    msg.payload = {
        value: 0, // 读取时value不重要
        fc: 3,    // 功能码3: 读取保持寄存器
        unitid: 1,
        address: start,
        quantity: qty
    };
    msg.tags = tags; // 保存所有相关的tag
    node.send(msg);
}

for (let i = 0; i < op10Points.length; i++) {
    const point = op10Points[i];
    
    // 如果是第一个点
    if (startAddress === null) {
        startAddress = point.address;
        currentAddress = point.address + point.length - 1; // 结束地址
        currentLength = point.length;
        quantity = point.length;
        tags = [point.tag];
        continue;
    }
    
    // 检查是否可以合并到当前请求中
    // 条件：地址连续且数据类型长度一致
    const isContinuous = (point.address === currentAddress + 1);
    const isSameLength = (point.length === currentLength);
    
    if (isContinuous && isSameLength) {
        currentAddress = point.address + point.length - 1;
        quantity += point.length;
        tags.push(point.tag);
    } else {
        // 发送当前的读取请求
        sendReadRequest(startAddress, quantity, tags);
        
        // 开始新的连续读取序列
        startAddress = point.address;
        currentAddress = point.address + point.length - 1;
        currentLength = point.length;
        quantity = point.length;
        tags = [point.tag];
    }
}

// 发送最后一个连续的读取请求
if (startAddress !== null && quantity > 0) {
    sendReadRequest(startAddress, quantity, tags);
}